﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Windows.Forms;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Analysis;   // HVACLoadSpaceType 在这里
using Autodesk.Revit.DB.Mechanical; // Space 可能也需要 (虽然此命令不直接用)
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection; // 如果需要选择
using Autodesk.Revit.Attributes;

// --- 使用别名避免冲突 ---
using WinForms = System.Windows.Forms;
using Drawing = System.Drawing;

namespace RevitApiExample // 请确保与您项目的命名空间一致
{
    //====================================================================
    // 主命令类: EditSpaceTypeCommand
    //====================================================================
    [Transaction(TransactionMode.Manual)]
    [Regeneration(RegenerationOption.Manual)]
    public class EditSpaceTypeCommand : IExternalCommand
    {
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument uidoc = uiapp.ActiveUIDocument;
            Document doc = uidoc.Document;

            // --- 1. 获取所有可用的空间类型 ---
            var allSpaceTypes = new FilteredElementCollector(doc)
                .OfClass(typeof(HVACLoadSpaceType))
                .Cast<HVACLoadSpaceType>()
                .OrderBy(st => st.Name)
                .ToList();

            if (!allSpaceTypes.Any())
            {
                TaskDialog.Show("信息", "项目中没有找到任何 HVAC 空间类型可供编辑。");
                return Result.Succeeded;
            }

            // --- 2. 让用户选择要编辑的类型 ---
            ElementId selectedTypeId = ElementId.InvalidElementId;
            using (var selectForm = new SelectTypeToEditForm(allSpaceTypes))
            {
                if (selectForm.ShowDialog() == WinForms.DialogResult.OK)
                {
                    selectedTypeId = selectForm.SelectedTypeId;
                }
                else
                {
                    return Result.Cancelled; // 用户取消选择
                }
            }

            if (selectedTypeId == null || selectedTypeId == ElementId.InvalidElementId)
            {
                // 基本上不会发生，因为表单会强制选择或取消
                return Result.Failed;
            }

            // --- 3. 获取要编辑的元素 ---
            HVACLoadSpaceType typeToEdit = doc.GetElement(selectedTypeId) as HVACLoadSpaceType;
            if (typeToEdit == null)
            {
                message = "无法找到所选的空间类型元素。可能已被删除。";
                TaskDialog.Show("错误", message);
                return Result.Failed;
            }

            // --- 4. 显示编辑窗体 ---
            EditedSpaceTypeData editedData = null;
            using (var editForm = new EditSpaceTypeForm(typeToEdit, doc))
            {
                if (editForm.ShowDialog() == WinForms.DialogResult.OK)
                {
                    editedData = editForm.ResultData; // 获取编辑后的数据（内部单位）
                }
                else
                {
                    return Result.Cancelled; // 用户在编辑界面取消
                }
            }

            // --- 5. 应用更改 ---
            if (editedData != null)
            {
                using (Transaction tx = new Transaction(doc, "编辑空间类型属性"))
                {
                    tx.Start();
                    try
                    {
                        // 重新获取元素以确保在事务内有效
                        HVACLoadSpaceType elementToUpdate = doc.GetElement(selectedTypeId) as HVACLoadSpaceType;
                        if (elementToUpdate == null)
                        {
                            throw new InvalidOperationException("在事务中无法找到要更新的空间类型。");
                        }

                        // 检查名称是否更改
                        if (elementToUpdate.Name != editedData.Name)
                        {
                            // 检查新名称是否唯一（可选但推荐）
                            bool isNameUnique = !new FilteredElementCollector(doc)
                                                  .OfClass(typeof(HVACLoadSpaceType))
                                                  .WhereElementIsNotElementType() // 确保排除自身比较（虽然这里获取的是ID不同的）
                                                  .Any(el => el.Id != elementToUpdate.Id && el.Name.Equals(editedData.Name, StringComparison.OrdinalIgnoreCase));

                            if (!isNameUnique)
                            {
                                tx.RollBack(); // 回滚事务
                                TaskDialog.Show("错误", $"名称 '{editedData.Name}' 已被另一个空间类型使用。请使用唯一名称。");
                                return Result.Failed;
                            }
                            elementToUpdate.Name = editedData.Name;
                        }

                        // 更新其他属性 (值已经是从表单传回的内部单位)
                        elementToUpdate.AreaPerPerson = editedData.AreaPerPersonInternal;
                        elementToUpdate.LightingLoadDensity = editedData.LightingLoadDensityInternal;
                        elementToUpdate.PowerLoadDensity = editedData.PowerLoadDensityInternal;
                        elementToUpdate.SensibleHeatGainPerPerson = editedData.SensibleHeatGainPerPersonInternal;
                        elementToUpdate.LatentHeatGainPerPerson = editedData.LatentHeatGainPerPersonInternal;
                        elementToUpdate.HeatingSetPoint = editedData.HeatingSetPointInternal;
                        elementToUpdate.CoolingSetPoint = editedData.CoolingSetPointInternal;

                        tx.Commit();
                        TaskDialog.Show("成功", $"空间类型 '{elementToUpdate.Name}' 的属性已成功更新。");
                        return Result.Succeeded;
                    }
                    catch (Exception ex)
                    {
                        tx.RollBack();
                        message = $"应用更改时出错: {ex.Message}";
                        TaskDialog.Show("错误", message);
                        return Result.Failed;
                    }
                }
            }

            return Result.Failed; // 如果 editedData 为 null (理论上不应发生)
        }
    }

    //====================================================================
    // 辅助窗体类: SelectTypeToEditForm (用于选择要编辑的类型)
    //====================================================================
    public class SelectTypeToEditForm : WinForms.Form
    {
        private WinForms.ListBox listBoxTypes;
        private WinForms.Button buttonOk;
        private WinForms.Button buttonCancel;
        private WinForms.Label labelInstruction;
        private Dictionary<string, ElementId> _typeMap;

        public ElementId SelectedTypeId { get; private set; } = ElementId.InvalidElementId;

        public SelectTypeToEditForm(IList<HVACLoadSpaceType> spaceTypes)
        {
            InitializeComponent();
            _typeMap = new Dictionary<string, ElementId>();

            foreach (var type in spaceTypes)
            {
                if (type != null && !string.IsNullOrEmpty(type.Name))
                {
                    // 使用更容易阅读的格式
                    string displayName = $"{type.Name} (ID: {type.Id.IntegerValue})";
                    if (!_typeMap.ContainsKey(displayName)) // 防止意外重名（虽然不太可能）
                    {
                        listBoxTypes.Items.Add(displayName);
                        _typeMap.Add(displayName, type.Id);
                    }
                }
            }

            if (listBoxTypes.Items.Count > 0)
            {
                listBoxTypes.SelectedIndex = 0; // 默认选中第一个
            }
            else
            {
                buttonOk.Enabled = false; // 如果没有类型，禁用确定按钮
            }
        }

        private void InitializeComponent()
        {
            this.listBoxTypes = new WinForms.ListBox();
            this.buttonOk = new WinForms.Button();
            this.buttonCancel = new WinForms.Button();
            this.labelInstruction = new WinForms.Label();
            this.SuspendLayout();

            // labelInstruction
            this.labelInstruction.AutoSize = true;
            this.labelInstruction.Location = new Drawing.Point(12, 15);
            this.labelInstruction.Name = "labelInstruction";
            this.labelInstruction.Size = new Drawing.Size(149, 13); // 根据中文调整
            this.labelInstruction.Text = "请选择要编辑的空间类型:";

            // listBoxTypes
            this.listBoxTypes.Anchor = ((WinForms.AnchorStyles)((((WinForms.AnchorStyles.Top | WinForms.AnchorStyles.Bottom)
            | WinForms.AnchorStyles.Left)
            | WinForms.AnchorStyles.Right)));
            this.listBoxTypes.FormattingEnabled = true;
            this.listBoxTypes.Location = new Drawing.Point(15, 35);
            this.listBoxTypes.Name = "listBoxTypes";
            this.listBoxTypes.Size = new Drawing.Size(300, 186); // 调整大小
            this.listBoxTypes.DoubleClick += (sender, e) => { ButtonOk_Click(sender, e); }; // 双击等于确定

            // buttonOk
            this.buttonOk.Anchor = ((WinForms.AnchorStyles)((WinForms.AnchorStyles.Bottom | WinForms.AnchorStyles.Right)));
            this.buttonOk.DialogResult = WinForms.DialogResult.OK;
            this.buttonOk.Location = new Drawing.Point(159, 230); // 调整位置
            this.buttonOk.Name = "buttonOk";
            this.buttonOk.Text = "确定";
            this.buttonOk.Click += new System.EventHandler(this.ButtonOk_Click);

            // buttonCancel
            this.buttonCancel.Anchor = ((WinForms.AnchorStyles)((WinForms.AnchorStyles.Bottom | WinForms.AnchorStyles.Right)));
            this.buttonCancel.DialogResult = WinForms.DialogResult.Cancel;
            this.buttonCancel.Location = new Drawing.Point(240, 230); // 调整位置
            this.buttonCancel.Name = "buttonCancel";
            this.buttonCancel.Text = "取消";

            // SelectTypeToEditForm
            this.AcceptButton = this.buttonOk;
            this.CancelButton = this.buttonCancel;
            this.ClientSize = new Drawing.Size(334, 261); // 调整大小
            this.Controls.Add(this.labelInstruction);
            this.Controls.Add(this.listBoxTypes);
            this.Controls.Add(this.buttonOk);
            this.Controls.Add(this.buttonCancel);
            this.FormBorderStyle = WinForms.FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.Name = "SelectTypeToEditForm";
            this.ShowIcon = false;
            this.ShowInTaskbar = false;
            this.StartPosition = WinForms.FormStartPosition.CenterParent;
            this.Text = "选择空间类型";
            this.ResumeLayout(false);
            this.PerformLayout();
        }

        private void ButtonOk_Click(object sender, EventArgs e)
        {
            if (listBoxTypes.SelectedItem != null)
            {
                string selectedDisplayName = listBoxTypes.SelectedItem.ToString();
                if (_typeMap.TryGetValue(selectedDisplayName, out ElementId selectedId))
                {
                    this.SelectedTypeId = selectedId;
                    this.DialogResult = WinForms.DialogResult.OK;
                }
                else
                {
                    // 理论上不应发生
                    WinForms.MessageBox.Show("无法找到所选项对应的 ID。", "内部错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    this.DialogResult = WinForms.DialogResult.None; // 阻止关闭
                }
            }
            else
            {
                WinForms.MessageBox.Show("请先选择一个空间类型。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                this.DialogResult = WinForms.DialogResult.None; // 阻止关闭
            }
        }
    }


    //====================================================================
    // 辅助窗体类: EditSpaceTypeForm (用于编辑属性)
    //====================================================================
    public class EditSpaceTypeForm : WinForms.Form
    {
        // --- 控件字段 ---
        private WinForms.Label lblName;
        private WinForms.TextBox txtName;
        private WinForms.Label lblIsPlenum;
        private WinForms.TextBox txtIsPlenum;
        private WinForms.Label lblAreaPerPerson;
        private WinForms.TextBox txtAreaPerPerson;
        private WinForms.Label lblAreaUnit;
        private WinForms.Label lblLightingLoad;
        private WinForms.TextBox txtLightingLoad;
        private WinForms.Label lblLightingUnit;
        private WinForms.Label lblPowerLoad;
        private WinForms.TextBox txtPowerLoad;
        private WinForms.Label lblPowerUnit;
        private WinForms.Label lblSensibleHeatGain;
        private WinForms.TextBox txtSensibleHeatGain;
        private WinForms.Label lblLatentHeatGain;
        private WinForms.TextBox txtLatentHeatGain;
        private WinForms.Label lblHeatGainUnit;
        private WinForms.Label lblHeatingSetpoint;
        private WinForms.TextBox txtHeatingSetpoint;
        private WinForms.Label lblCoolingSetpoint;
        private WinForms.TextBox txtCoolingSetpoint;
        private WinForms.Label lblTempUnit;
        private WinForms.Button btnOk;
        private WinForms.Button btnCancel;

        // --- 公开属性，用于传递编辑后的数据 (以内部单位存储) ---
        public EditedSpaceTypeData ResultData { get; private set; }

        // --- 私有字段 ---
        private readonly HVACLoadSpaceType _originalType;
        private readonly Document _doc; // 可能需要用于旧版单位转换API

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="typeToEdit">要编辑的空间类型</param>
        /// <param name="doc">Revit 文档</param>
        public EditSpaceTypeForm(HVACLoadSpaceType typeToEdit, Document doc)
        {
            _originalType = typeToEdit ?? throw new ArgumentNullException(nameof(typeToEdit));
            _doc = doc; // 如果使用新版ForgeTypeId则不需要doc
            InitializeComponent();
            LoadData(); // 加载初始数据
        }

        /// <summary>
        /// 初始化窗体控件 (代码同上一回答中的InitializeComponent)
        /// </summary>
        private void InitializeComponent()
        {
            // ... (此处省略与上一回答中完全相同的 InitializeComponent 代码) ...
            // ... 请将上一回答中的 InitializeComponent 方法完整复制到这里 ...
            // ... 确保包含了所有控件的创建和布局 ...

            // !!! 重要: 确保 InitializeComponent 方法最后调用了:
            // this.btnOk.Click += new System.EventHandler(this.BtnOk_Click);
            // this.btnCancel.Click += (sender, e) => { this.DialogResult = DialogResult.Cancel; }; // 可选，DialogResult属性通常足够
            // this.ResumeLayout(false);
            // this.PerformLayout();

            // --- 为简洁，此处省略重复代码，请从上面回答复制 ---
            this.lblName = new WinForms.Label();
            this.txtName = new WinForms.TextBox();
            this.lblIsPlenum = new WinForms.Label();
            this.txtIsPlenum = new WinForms.TextBox();
            this.lblAreaPerPerson = new WinForms.Label();
            this.txtAreaPerPerson = new WinForms.TextBox();
            this.lblAreaUnit = new WinForms.Label();
            this.lblLightingLoad = new WinForms.Label();
            this.txtLightingLoad = new WinForms.TextBox();
            this.lblLightingUnit = new WinForms.Label();
            this.lblPowerLoad = new WinForms.Label();
            this.txtPowerLoad = new WinForms.TextBox();
            this.lblPowerUnit = new WinForms.Label();
            this.lblSensibleHeatGain = new WinForms.Label();
            this.txtSensibleHeatGain = new WinForms.TextBox();
            this.lblLatentHeatGain = new WinForms.Label();
            this.txtLatentHeatGain = new WinForms.TextBox();
            this.lblHeatGainUnit = new WinForms.Label();
            this.lblHeatingSetpoint = new WinForms.Label();
            this.txtHeatingSetpoint = new WinForms.TextBox();
            this.lblCoolingSetpoint = new WinForms.Label();
            this.txtCoolingSetpoint = new WinForms.TextBox();
            this.lblTempUnit = new WinForms.Label();
            this.btnOk = new WinForms.Button();
            this.btnCancel = new WinForms.Button();

            this.SuspendLayout();

            int top = 15;
            int leftLabel = 15;
            int leftText = 180;
            int leftUnit = 300;
            int spacing = 30;
            int textBoxWidth = 100;
            int formWidth = 420;

            // 名称
            this.lblName.Location = new Drawing.Point(leftLabel, top);
            this.lblName.Text = "名称:"; this.lblName.AutoSize = true;
            this.txtName.Location = new Drawing.Point(leftText, top - 2); this.txtName.Size = new Drawing.Size(200, 20); this.txtName.TabIndex = 0; this.txtName.ReadOnly = false;
            top += spacing;
            // 是否为静压箱 (只读)
            this.lblIsPlenum.Location = new Drawing.Point(leftLabel, top);
            this.lblIsPlenum.Text = "是否为静压箱:"; this.lblIsPlenum.AutoSize = true;
            this.txtIsPlenum.Location = new Drawing.Point(leftText, top - 2); this.txtIsPlenum.Size = new Drawing.Size(200, 20); this.txtIsPlenum.ReadOnly = true; this.txtIsPlenum.TabStop = false; this.txtIsPlenum.BackColor = System.Drawing.SystemColors.Control;
            top += spacing;
            // 人均面积
            this.lblAreaPerPerson.Location = new Drawing.Point(leftLabel, top);
            this.lblAreaPerPerson.Text = "人均面积:"; this.lblAreaPerPerson.AutoSize = true;
            this.txtAreaPerPerson.Location = new Drawing.Point(leftText, top - 2); this.txtAreaPerPerson.Size = new Drawing.Size(textBoxWidth, 20); this.txtAreaPerPerson.TabIndex = 1;
            this.lblAreaUnit.Location = new Drawing.Point(leftUnit, top); this.lblAreaUnit.Text = "m²/人"; this.lblAreaUnit.AutoSize = true;
            top += spacing;
            // 照明负荷密度
            this.lblLightingLoad.Location = new Drawing.Point(leftLabel, top);
            this.lblLightingLoad.Text = "照明负荷密度:"; this.lblLightingLoad.AutoSize = true;
            this.txtLightingLoad.Location = new Drawing.Point(leftText, top - 2); this.txtLightingLoad.Size = new Drawing.Size(textBoxWidth, 20); this.txtLightingLoad.TabIndex = 2;
            this.lblLightingUnit.Location = new Drawing.Point(leftUnit, top); this.lblLightingUnit.Text = "W/m²"; this.lblLightingUnit.AutoSize = true;
            top += spacing;
            // 设备负荷密度
            this.lblPowerLoad.Location = new Drawing.Point(leftLabel, top);
            this.lblPowerLoad.Text = "设备负荷密度:"; this.lblPowerLoad.AutoSize = true;
            this.txtPowerLoad.Location = new Drawing.Point(leftText, top - 2); this.txtPowerLoad.Size = new Drawing.Size(textBoxWidth, 20); this.txtPowerLoad.TabIndex = 3;
            this.lblPowerUnit.Location = new Drawing.Point(leftUnit, top); this.lblPowerUnit.Text = "W/m²"; this.lblPowerUnit.AutoSize = true;
            top += spacing;
            // 人员显热
            this.lblSensibleHeatGain.Location = new Drawing.Point(leftLabel, top);
            this.lblSensibleHeatGain.Text = "人员显热:"; this.lblSensibleHeatGain.AutoSize = true;
            this.txtSensibleHeatGain.Location = new Drawing.Point(leftText, top - 2); this.txtSensibleHeatGain.Size = new Drawing.Size(textBoxWidth, 20); this.txtSensibleHeatGain.TabIndex = 4;
            top += spacing;
            // 人员潜热
            this.lblLatentHeatGain.Location = new Drawing.Point(leftLabel, top);
            this.lblLatentHeatGain.Text = "人员潜热:"; this.lblLatentHeatGain.AutoSize = true;
            this.txtLatentHeatGain.Location = new Drawing.Point(leftText, top - 2); this.txtLatentHeatGain.Size = new Drawing.Size(textBoxWidth, 20); this.txtLatentHeatGain.TabIndex = 5;
            this.lblHeatGainUnit.Location = new Drawing.Point(leftUnit, top - (spacing / 2)); this.lblHeatGainUnit.Text = "W/人"; this.lblHeatGainUnit.AutoSize = true;
            top += spacing;
            // 供暖设定点
            this.lblHeatingSetpoint.Location = new Drawing.Point(leftLabel, top);
            this.lblHeatingSetpoint.Text = "供暖设定点:"; this.lblHeatingSetpoint.AutoSize = true;
            this.txtHeatingSetpoint.Location = new Drawing.Point(leftText, top - 2); this.txtHeatingSetpoint.Size = new Drawing.Size(textBoxWidth, 20); this.txtHeatingSetpoint.TabIndex = 6;
            top += spacing;
            // 制冷设定点
            this.lblCoolingSetpoint.Location = new Drawing.Point(leftLabel, top);
            this.lblCoolingSetpoint.Text = "制冷设定点:"; this.lblCoolingSetpoint.AutoSize = true;
            this.txtCoolingSetpoint.Location = new Drawing.Point(leftText, top - 2); this.txtCoolingSetpoint.Size = new Drawing.Size(textBoxWidth, 20); this.txtCoolingSetpoint.TabIndex = 7;
            this.lblTempUnit.Location = new Drawing.Point(leftUnit, top - (spacing / 2)); this.lblTempUnit.Text = "°C"; this.lblTempUnit.AutoSize = true;
            top += spacing + 10;

            // 确定按钮
            this.btnOk.Location = new Drawing.Point(formWidth - 175, top); this.btnOk.Name = "btnOk"; this.btnOk.Size = new Drawing.Size(75, 23); this.btnOk.TabIndex = 8; this.btnOk.Text = "确定"; this.btnOk.UseVisualStyleBackColor = true;
            this.btnOk.Click += new System.EventHandler(this.BtnOk_Click); // 绑定确定按钮事件

            // 取消按钮
            this.btnCancel.DialogResult = WinForms.DialogResult.Cancel;
            this.btnCancel.Location = new Drawing.Point(formWidth - 90, top); this.btnCancel.Name = "btnCancel"; this.btnCancel.Size = new Drawing.Size(75, 23); this.btnCancel.TabIndex = 9; this.btnCancel.Text = "取消"; this.btnCancel.UseVisualStyleBackColor = true;

            // 窗体设置
            this.AcceptButton = this.btnOk;
            this.CancelButton = this.btnCancel;
            this.ClientSize = new Drawing.Size(formWidth, top + 40);
            this.Controls.Add(this.lblName); this.Controls.Add(this.txtName);
            this.Controls.Add(this.lblIsPlenum); this.Controls.Add(this.txtIsPlenum);
            this.Controls.Add(this.lblAreaPerPerson); this.Controls.Add(this.txtAreaPerPerson); this.Controls.Add(this.lblAreaUnit);
            this.Controls.Add(this.lblLightingLoad); this.Controls.Add(this.txtLightingLoad); this.Controls.Add(this.lblLightingUnit);
            this.Controls.Add(this.lblPowerLoad); this.Controls.Add(this.txtPowerLoad); this.Controls.Add(this.lblPowerUnit);
            this.Controls.Add(this.lblSensibleHeatGain); this.Controls.Add(this.txtSensibleHeatGain);
            this.Controls.Add(this.lblLatentHeatGain); this.Controls.Add(this.txtLatentHeatGain); this.Controls.Add(this.lblHeatGainUnit);
            this.Controls.Add(this.lblHeatingSetpoint); this.Controls.Add(this.txtHeatingSetpoint);
            this.Controls.Add(this.lblCoolingSetpoint); this.Controls.Add(this.txtCoolingSetpoint); this.Controls.Add(this.lblTempUnit);
            this.Controls.Add(this.btnOk); this.Controls.Add(this.btnCancel);
            this.FormBorderStyle = WinForms.FormBorderStyle.FixedDialog;
            this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "EditSpaceTypeForm";
            this.ShowIcon = false; this.ShowInTaskbar = false; this.StartPosition = WinForms.FormStartPosition.CenterParent; this.Text = "编辑空间类型";
            this.ResumeLayout(false);
            this.PerformLayout();

        }


        /// <summary>
        /// 加载原始数据到窗体控件，并进行单位转换
        /// </summary>
        private void LoadData()
        {
            if (_originalType == null) return;

            txtName.Text = _originalType.Name;
            txtIsPlenum.Text = _originalType.IsPlenum ? "是" : "否";

            // 单位转换： 从 Revit 内部单位 转换为 显示单位
            try
            {
                // 人均面积 (ft² -> m²) - 注意：API单位是 ft², 显示单位是 m²/人
                if (_originalType.AreaPerPerson > 1e-9) // 检查是否大于一个很小的值避免无效转换
                {
                    // Convert ft² to m²
                    double areaM2 = UnitUtils.ConvertFromInternalUnits(_originalType.AreaPerPerson, UnitTypeId.SquareFeet);
                    txtAreaPerPerson.Text = areaM2.ToString("F2", CultureInfo.InvariantCulture); // 保留两位小数
                }
                else { txtAreaPerPerson.Text = "0"; }


                // 照明负荷密度 (W/ft² -> W/m²)
                double lightW_m2 = UnitUtils.ConvertFromInternalUnits(_originalType.LightingLoadDensity, UnitTypeId.WattsPerSquareFoot);
                txtLightingLoad.Text = lightW_m2.ToString("F2", CultureInfo.InvariantCulture);

                // 设备负荷密度 (W/ft² -> W/m²)
                double powerW_m2 = UnitUtils.ConvertFromInternalUnits(_originalType.PowerLoadDensity, UnitTypeId.WattsPerSquareFoot);
                txtPowerLoad.Text = powerW_m2.ToString("F2", CultureInfo.InvariantCulture);

                // 人员显热 (内部单位: Watts -> 显示单位: W)
                // 因为内部和显示单位都是 W，直接赋值
                double sensibleW = _originalType.SensibleHeatGainPerPerson;
                txtSensibleHeatGain.Text = sensibleW.ToString("F2", CultureInfo.InvariantCulture);

                // 人员潜热 (内部单位: Watts -> 显示单位: W)
                // 因为内部和显示单位都是 W，直接赋值
                double latentW = _originalType.LatentHeatGainPerPerson;
                txtLatentHeatGain.Text = latentW.ToString("F2", CultureInfo.InvariantCulture);
                txtLatentHeatGain.Text = latentW.ToString("F2", CultureInfo.InvariantCulture);

                // 供暖设定点 (K 或 R -> °C)
                double heatC = UnitUtils.ConvertFromInternalUnits(_originalType.HeatingSetPoint, UnitTypeId.Celsius);
                txtHeatingSetpoint.Text = heatC.ToString("F1", CultureInfo.InvariantCulture); // 保留一位小数

                // 制冷设定点 (K 或 R -> °C)
                double coolC = UnitUtils.ConvertFromInternalUnits(_originalType.CoolingSetPoint, UnitTypeId.Celsius);
                txtCoolingSetpoint.Text = coolC.ToString("F1", CultureInfo.InvariantCulture);
            }
            catch (Exception ex)
            {
                // 处理可能的单位转换错误
                MessageBox.Show($"加载数据时发生单位转换错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                // 可以考虑禁用确定按钮或关闭窗口
                this.DialogResult = DialogResult.Abort; // Indicate failure
            }
        }


        /// <summary>
        /// “确定”按钮点击事件：解析输入、转换单位、设置结果并关闭窗口
        /// </summary>
        private void BtnOk_Click(object sender, EventArgs e)
        {
            // --- 1. 创建结果数据对象 ---
            var data = new EditedSpaceTypeData();

            // --- 2. 验证和解析输入 ---
            List<string> errors = new List<string>();

            // 名称
            data.Name = txtName.Text.Trim();
            if (string.IsNullOrWhiteSpace(data.Name))
            {
                errors.Add("名称不能为空。");
            }

            // 解析数值 (使用 InvariantCulture 避免小数点问题)
            double areaPerPerson_m2 = 0, lighting_W_m2 = 0, power_W_m2 = 0;
            double sensible_W = 0, latent_W = 0, heating_C = 0, cooling_C = 0;

            if (!double.TryParse(txtAreaPerPerson.Text, NumberStyles.Any, CultureInfo.InvariantCulture, out areaPerPerson_m2) || areaPerPerson_m2 < 0) errors.Add("人均面积必须是有效的非负数字。");
            if (!double.TryParse(txtLightingLoad.Text, NumberStyles.Any, CultureInfo.InvariantCulture, out lighting_W_m2) || lighting_W_m2 < 0) errors.Add("照明负荷密度必须是有效的非负数字。");
            if (!double.TryParse(txtPowerLoad.Text, NumberStyles.Any, CultureInfo.InvariantCulture, out power_W_m2) || power_W_m2 < 0) errors.Add("设备负荷密度必须是有效的非负数字。");
            if (!double.TryParse(txtSensibleHeatGain.Text, NumberStyles.Any, CultureInfo.InvariantCulture, out sensible_W) || sensible_W < 0) errors.Add("人员显热必须是有效的非负数字。");
            if (!double.TryParse(txtLatentHeatGain.Text, NumberStyles.Any, CultureInfo.InvariantCulture, out latent_W) || latent_W < 0) errors.Add("人员潜热必须是有效的非负数字。");
            if (!double.TryParse(txtHeatingSetpoint.Text, NumberStyles.Any, CultureInfo.InvariantCulture, out heating_C)) errors.Add("供暖设定点必须是有效的数字。");
            if (!double.TryParse(txtCoolingSetpoint.Text, NumberStyles.Any, CultureInfo.InvariantCulture, out cooling_C)) errors.Add("制冷设定点必须是有效的数字。");

            // 可选：添加逻辑检查，例如制冷设定点应高于供暖设定点
            if (errors.Count == 0 && cooling_C <= heating_C)
            {
                errors.Add("制冷设定点应高于供暖设定点。");
            }

            // 如果有错误，显示错误信息并不关闭窗口
            if (errors.Count > 0)
            {
                MessageBox.Show("输入无效:\n- " + string.Join("\n- ", errors), "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return; // 保持窗口打开
            }

            // --- 3. 单位转换：从 显示单位 转换为 Revit 内部单位 ---
            try
            {
                // 人均面积 (m² -> ft²) 注意API单位是 ft²
                data.AreaPerPersonInternal = UnitUtils.ConvertToInternalUnits(areaPerPerson_m2, UnitTypeId.SquareFeet);

                // 照明负荷密度 (W/m² -> W/ft²)
                data.LightingLoadDensityInternal = UnitUtils.ConvertToInternalUnits(lighting_W_m2, UnitTypeId.WattsPerSquareFoot);

                // 设备负荷密度 (W/m² -> W/ft²)
                data.PowerLoadDensityInternal = UnitUtils.ConvertToInternalUnits(power_W_m2, UnitTypeId.WattsPerSquareFoot);

                // 人员显热 (显示单位: W -> 内部单位: Watts)
                // 因为内部和显示单位都是 W，直接赋值
                data.SensibleHeatGainPerPersonInternal = sensible_W;

                // 人员潜热 (显示单位: W -> 内部单位: Watts)
                // 因为内部和显示单位都是 W，直接赋值
                data.LatentHeatGainPerPersonInternal = latent_W;

                // 供暖设定点 (°C -> K 或 R)
                data.HeatingSetPointInternal = UnitUtils.ConvertToInternalUnits(heating_C, UnitTypeId.Celsius);

                // 制冷设定点 (°C -> K 或 R)
                data.CoolingSetPointInternal = UnitUtils.ConvertToInternalUnits(cooling_C, UnitTypeId.Celsius);

                // --- 4. 设置结果并关闭 ---
                this.ResultData = data;
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存数据时发生单位转换错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                // 保持窗口打开或设置 Abort 状态
                // this.DialogResult = DialogResult.Abort;
            }
        }

    }


    //====================================================================
    // 辅助类: EditedSpaceTypeData (用于在窗体和命令间传递数据)
    //====================================================================
    public class EditedSpaceTypeData
    {
        public string Name { get; set; } // 编辑后的名称

        // 注意：以下属性存储的是 Revit 的【内部单位】值
        public double AreaPerPersonInternal { get; set; } // ft²
        public double LightingLoadDensityInternal { get; set; } // W/ft²
        public double PowerLoadDensityInternal { get; set; } // W/ft²
        public double SensibleHeatGainPerPersonInternal { get; set; } // BTU/h
        public double LatentHeatGainPerPersonInternal { get; set; } // BTU/h
        public double HeatingSetPointInternal { get; set; } // K or R
        public double CoolingSetPointInternal { get; set; } // K or R
    }

} // end namespace